<template>
  <div class="merchant-list">
    <el-card class="mb-4">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="反馈标题">
          <el-input v-model="searchForm.title" placeholder="请输入反馈标题" clearable class="w-60" />
        </el-form-item>
        <el-form-item label="商铺">
          <el-select filterable  v-model="searchForm.merchantId" clearable placeholder="请选择商铺">
            <el-option :label="item.name" :value="item.id" v-for="item,index in merchantList" :key="index" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="handleAdd" style="margin-left: 30px"
            v-has="'shop:feedback:save'">新增意见</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  
    <!-- 表格 -->
    <el-table v-loading="loading" :data="tableData" border style="width: 100%;margin-top:15px">
      <el-table-column prop="id" label="ID" width="80" />
      <!-- <el-table-column prop="shopName" label="商铺名称" /> -->
      <el-table-column prop="title" label="反馈标题" />
      <el-table-column prop="content" label="反馈内容" />
      <el-table-column prop="images" label="反馈图片" width="120">
        <template #default="{ row }">
          <el-image v-if="row.images" style="width: 80px; height: 80px" :src="row.images[0]"
            :preview-src-list="row.images ? row.images : []" fit="cover" />
        </template>
      </el-table-column>
      <el-table-column prop="feedbackType" label="反馈类型" width="120">
        <template #default="{ row }">
          <el-tag v-if="row.feedbackType === 1" type="danger">产品问题</el-tag>
          <el-tag v-if="row.feedbackType === 2" type="warning">服务问题</el-tag>
          <el-tag v-if="row.feedbackType === 3" type="success">建议</el-tag>
          <el-tag v-if="row.feedbackType === 4" type="info">其他</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="feedbackStatus" label="反馈状态" width="120">
        <template #default="{ row }">
          <el-tag v-if="row.feedbackStatus === 0" type="danger">未处理</el-tag>
          <el-tag v-if="row.feedbackStatus === 1" type="warning">处理中</el-tag>
          <el-tag v-if="row.feedbackStatus === 2" type="success">已解决</el-tag>
          <el-tag v-if="row.feedbackStatus === 3" type="info">已关闭</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="priority" label="优先级" width="120">
        <template #default="{ row }">
          <el-tag v-if="row.priority === 1" type="danger">低</el-tag>
          <el-tag v-if="row.priority === 2" type="warning">中</el-tag>
          <el-tag v-if="row.priority === 3" type="success">高</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button type="text" v-has="'shop:feedback:update'" @click="handleEdit(row)">编辑</el-button>
          <el-button type="text" style="color: #f56c6c" v-has="'shop:feedback:delete'"
            @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next" :total="total">
      </el-pagination>
    </div>
  
    <!-- 新增/编辑弹窗 -->
    <el-dialog :close-on-click-modal="false"  :title="dialogType === 'add' ? '新增意见' : '编辑意见'" :visible.sync="dialogVisible" width="80%"
      @close="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" class="dialog_height">
        <el-form-item label="商铺" prop="merchantId">
          <el-select filterable  v-model="form.merchantId" placeholder="请选择商铺" style="width: 100%">
            <el-option :label="item.name" :value="item.id" v-for="item,index in merchantList" :key="index" />
          </el-select>
        </el-form-item>
        <el-form-item label="反馈标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入反馈标题" />
        </el-form-item>
        <el-form-item label="反馈内容" prop="content">
          <el-input type="textarea" v-model="form.content" placeholder="请输入反馈内容" :rows="3" />
        </el-form-item>
        <el-form-item label="商铺图片" prop="images">
          <el-upload class="image-uploader" :show-file-list="false" :on-success="handleBannerSuccess" :headers="headers"
            :action="$uploadUrl" :before-upload="beforeImageUpload1">
            <div class="flex_flex">
              <div v-for="item,index in form.images" :key="index" class="image-item">
                <img :src="item" class="uploaded-image" />
                <div class="delete-image" @click="handleDeleteImage(index)">删除</div>
              </div>
              <div class="upload-placeholder">
                <i class="el-icon-plus"></i>
                <div class="upload-text">点击上传图片</div>
              </div>
            </div>
          </el-upload>
          <!-- <div class="form-tip">建议尺寸：200x200px，支持jpg、png格式</div> -->
        </el-form-item>
        <el-form-item label="反馈类型" prop="feedbackType">
          <el-select filterable  v-model="form.feedbackType" placeholder="请选择反馈类型">
            <el-option label="产品问题" :value="1"></el-option>
            <el-option label="服务问题" :value="2"></el-option>
            <el-option label="建议" :value="3"></el-option>
            <el-option label="其他" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="反馈状态" prop="feedbackStatus">
          <el-select filterable  v-model="form.feedbackStatus" placeholder="请选择反馈状态">
            <el-option label="未处理" :value="0"></el-option>
            <el-option label="处理中" :value="1"></el-option>
            <el-option label="已解决" :value="2"></el-option>
            <el-option label="已关闭" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select filterable  v-model="form.priority" placeholder="请选择优先级">
            <el-option label="低" :value="1"></el-option>
            <el-option label="中" :value="2"></el-option>
            <el-option label="高" :value="3"></el-option>
          </el-select>
        </el-form-item>
  
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'MerchantList',
  data() {
    return {
      headers: {
        'token': localStorage.getItem('token')
      },
      // 搜索表单
      searchForm: {
        title: '',
        merchantId: ''
      },
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 表格数据
      tableData: [],
      loading: false,
      // 弹窗相关
      dialogVisible: false,
      dialogType: 'add', // add 或 edit
      uploadUrl: '', // 上传地址
      form: {
        merchantId: '',
        title: '',
        content: '',
        images: [],
        feedbackType: '',
        feedbackStatus: '',
        priority: ''
      },
      // 表单校验规则
      rules: {
        merchantId: [{ required: true, message: '请选择商户', trigger: 'blur' }],
        title: [{ required: true, message: '请输入反馈标题', trigger: 'blur' }],
        content: [{ required: true, message: '请输入反馈内容', trigger: 'blur' }],
        feedbackType: [{ required: true, message: '请选择反馈类型', trigger: 'blur' }],
        feedbackStatus: [{ required: true, message: '请选择反馈状态', trigger: 'blur' }],
        priority: [{ required: true, message: '请选择优先级', trigger: 'blur' }],
        images: [{ required: true, message: '请上传反馈图片', trigger: 'blur' }]
      },
      merchantList: []
    }
  },
  created() {
    this.getMerchantList()
  },
  methods: {
    async beforeImageUpload1(rawFile) {
      const fileName = rawFile.name
      // const baseFileName = fileName.substring(0, fileName.lastIndexOf('.'))
      // const { data } = await this.$api.getUploadUrl({ filename: fileName })
      // console.log(data, 'data');
      // this.action = data.result.url
      // this.fileKey = data.result.fileKey
      // this.bannerUploadUrl = data.result.uploadUrl
      const imgSize = rawFile.size / 1024 / 1024 < 10
      const imgType = ['image/jpeg', 'image/png', 'image/gif']
      if (!imgType.includes(rawFile.type))
        message.notifyWarning('上传图片不符合所需的格式！')
      if (!imgSize) message.notifyWarning(`上传图片大小不能超过 10M！`)
      return imgType.includes(rawFile.type) && imgSize
    },
    async handleBannerSuccess(res) {
      this.form.images.push(res.result.filePath)
    },
    handleDeleteImage(index) {
      this.form.images.splice(index, 1)
    },
    async getMerchantList() {
      const { data } = await this.$api.shopPageList({
        page: 1,
        size: 10000,
        condition: {
          categoryId: '',
          areaId: '',
          floorId: '',
        }
      })
      console.log(data, '111111');
      this.merchantList = data.result.records
      this.getList();
    },
    // 获取列表数据
    async getList() {
      this.loading = true
      try {
        const { data } = await this.$api.getMerchantViewList({
          page: this.currentPage,
          size: this.pageSize,
          condition: {
            ...this.searchForm
          }
        })
        // data.result.records.forEach(item => {
        //   item.merchantName = this.merchantList.find(merchant => merchant.id === item.merchantId)?.name
        // })
        this.tableData = data.result.records
        this.total = data.result.total
      } catch (error) {
        console.error('获取商家列表失败：', error)
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.getList()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        name: '',
        title: '',
        phone: ''
      }
      this.handleSearch()
    },

    // 分页相关
    handleSizeChange(val) {
      this.pageSize = val
      this.getList()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    },

    // 新增
    handleAdd() {
      this.dialogType = 'add'
      this.dialogVisible = true
    },

    // 编辑
    handleEdit(row) {
      this.dialogType = 'edit'
      this.form = { ...row }
      this.dialogVisible = true
    },

    // 删除
    handleDelete(row) {
      this.$confirm('确认删除该意见吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await this.$api.deleteMerchantView(row.id)
          this.$message.success('删除成功')
          this.getList()
        } catch (error) {
          console.error('删除失败：', error)
        }
      }).catch(() => { })
    },

    // 上传相关
    handleUploadSuccess(res) {
      this.form.images = res.result.filePath

    },

    beforeUpload(rawFile) {
      const imgSize = rawFile.size / 1024 / 1024 < 10
      const imgType = ['image/jpeg', 'image/png', 'image/gif']
      if (!imgType.includes(rawFile.type))
        message.notifyWarning('上传图片不符合所需的格式！')
      if (!imgSize) message.notifyWarning(`上传图片大小不能超过 10M！`)
      return imgType.includes(rawFile.type) && imgSize
    },

    // 提交表单
    handleSubmit() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            if (this.dialogType === 'add') {
              await this.$api.addMerchantView(this.form)
              this.$message.success('新增成功')
            } else {
              await this.$api.editMerchantView(this.form)
              this.$message.success('编辑成功')
            }
            this.dialogVisible = false
            this.getList()
          } catch (error) {
            console.error(this.dialogType === 'add' ? '新增失败：' : '编辑失败：', error)
          }
        }
      })
    },

    // 重置表单
    resetForm() {
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields()
      }
      this.form = {
        merchantId: '',
        title: '',
        content: '',
        images: [],
        feedbackType: '',
        feedbackStatus: '',
        priority: ''
      }
    }
  }
}
</script>

<style scoped lang="scss">
.dialog_height{
    // height: 50vh;
    overflow: hidden;
    overflow-y: auto;
}
.image-item {
  position: relative;
}

.delete-image {
  position: absolute;
  bottom: 15px;
  right: 0px;
  width: 100%;
  height: 20px;
  font-size: 14px;
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
  cursor: pointer;
  z-index: 1000;
  line-height: 20px;
}

.flex_flex {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.image-uploader {
  .uploaded-image {
    width: 140px;
    height: 140px;
    object-fit: cover;
    border-radius: 4px;
  }

  .upload-placeholder {
    width: 140px;
    height: 140px;
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: border-color 0.3s;

    &:hover {
      border-color: #409EFF;
    }

    .el-icon-plus {
      font-size: 28px;
      color: #8c939d;
    }

    .upload-text {
      font-size: 12px;
      color: #8c939d;
      margin-top: 8px;
    }
  }
}

.merchant-list {
  padding: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>